package logic

import (
	"context"
	"github.com/golang-jwt/jwt/v4"
	"time"

	"HD_running/mall/order/api/internal/svc"
	"HD_running/mall/order/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *LoginLogic) Login(req *types.LoginReq) (resp *types.LoginResp, err error) {
	// todo: add your logic here and delete this line
	info, err := l.svcCtx.StudentcourseModel.FindOne(l.ctx, req.Sno)
	if err != nil {
		return nil, err
	}
	iat := time.Now().Unix()
	seconds := l.svcCtx.Config.Token.AccessExpire
	userId := info.Sno
	_, err = l.getJwtToken(l.svcCtx.Config.Token.AccessSecret, iat, seconds, userId)
	if info.Password1 == req.Password {
		return &types.LoginResp{
			Msg:   "登陆成功",
			Sname: info.Sname,
			Cno:   info.Cno,
		}, nil
	} else {
		return &types.LoginResp{
			Msg:   "密码错误",
			Sname: "密码错误",
			Cname: "密码错误",
		}, nil
	}

}
func (l *LoginLogic) getJwtToken(secretKey string, iat, seconds int64, userId string) (string, error) {
	claims := make(jwt.MapClaims)
	claims["exp"] = iat + seconds
	claims["iat"] = iat
	claims["userId"] = userId
	token := jwt.New(jwt.SigningMethodHS256)
	token.Claims = claims
	return token.SignedString([]byte(secretKey))
}
